﻿using Interface.Core.Controllers;
using Interface.Core.Utility;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Mvc;

namespace Interface.Mvc.Areas.Scrm.Controllers
{
    public class CategoryController : CoreController
    {
        /// <summary>
        /// 获取全部节点 
        /// url: /scrm/category/query
        /// params: 
        /// </summary>
        [HttpGet]
        public string Query()
        {
            var sql = new StringBuilder();

            sql.Append("Select ID, PID, PPath, Code, Name, IconFont, IconImage ");
            sql.Append("From Product_Category(nolock) ");
            sql.Append("Where Effective = 1 ");
            sql.Append("Order By Sequence");

            var list = db.Scrm.Query<dynamic>(sql.ToString());

            return ResultUtility.SuccessResult(data: list);
        }

        /// <summary>
        /// 根据父级编号获取分类 
        /// url: /scrm/category/getbypid
        /// params: pid, top
        /// </summary>
        [HttpGet]
        public string GetByPid(int pid, int top)
        {
            var sql = new StringBuilder();

            sql.Append("Select ");

            if (top > 0)
            {
                sql.AppendFormat("Top {0} ", top);
            }

            sql.Append("ID, PID, PPath, Code, Name, IconFont, IconImage ");
            sql.Append("From Product_Category(nolock) ");
            sql.Append("Where PID = @PID And Effective = 1 ");
            sql.Append("Order By Sequence");

            var list = db.Scrm.Query<dynamic>(sql.ToString(), new { PID = pid });

            return ResultUtility.SuccessResult(data: list);
        }

        /// <summary>
        /// 根据父级编号获取子孙分类 
        /// url: /scrm/category/getchildbypid
        /// params: pid
        /// </summary>
        [HttpGet]
        public string GetChildByPid(int pid)
        {
            var sql = new StringBuilder();

            sql.Append("Select ID, PID, PPath, Code, Name, IconFont, IconImage ");
            sql.Append("From Product_Category(nolock) ");
            sql.Append("Where CHARINDEX(@PID, PPath) > 0 And Effective = 1 ");
            sql.Append("Order By Sequence");

            var list = db.Scrm.Query<dynamic>(sql.ToString(), new { PID = string.Format("|{0}|", pid) });

            return ResultUtility.SuccessResult(data: list);
        }
    }
}
